package com.coder.algorithm.offer_2;

/**
 * 字符串的排列
 *
 * @author yuhushuan
 * @date 2020/6/24 11:39
 */
public class _38_1_StringPermutation {

    private static void permutation(String src) {
        if (src == null) {
            return;
        }
        permutationCore(src.toCharArray(), 0);
    }

    private static void permutationCore(char[] src, int index) {
        if (src == null) {
            return;
        }
        if (index == src.length - 1) {
            System.out.println(src);
            return;
        }
        for (int i = index; i < src.length; ++i) {
            if (i != index) {// 交换
                char temp = src[i];
                src[i] = src[index];
                src[index] = temp;
            }
            permutationCore(src, index + 1);
            if (i != index) {// 交换回来
                char temp = src[i];
                src[i] = src[index];
                src[index] = temp;
            }
        }
    }

    private static void permutationCore(String src, String dest) {
        if (src == null) {
            return;
        }
        if (src.length() == 1) {
            System.out.println(dest + src);
            return;
        }
        for (int i = 0; i < src.length(); ++i) {
            char first = src.charAt(i);
            String newSrc = new StringBuilder(src).deleteCharAt(i).toString();
            permutationCore(newSrc, dest + first);
        }
    }


    public static void main(String[] args) {
        // 功能测试
        // 一个字符
        permutation("a");
        // 多个字符
        permutation("abc");
        // 特殊输入测试
        permutation("");
        permutation(null);
    }

}
